
var Moment = require("../../utils/moment.js");
var DATE_LIST = [];
var DATE_YEAR = new Date().getFullYear();
var DATE_MONTH = new Date().getMonth() + 1;
var DATE_DAY = new Date().getDate();
let app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    checkInDate:{
      type: String,
      value: Moment(new Date()).format('YYYY-MM-DD')
    },
    checkOutDate:{
      type: String,
      value: Moment(new Date()).add(1, 'day').format('YYYY-MM-DD'),
    },
    checkInWeek:{
      type: String,
      value: Moment(new Date()).getWeek(Moment(new Date()).format('YYYY-MM-DD'))
    },
    checkOutWeek:{
      type: String,
      value: Moment(new Date()).getWeek(Moment(new Date()).add(1, 'day').format('YYYY-MM-DD'))
    },
    soldOutList:{//已售罄的日期
      type:Array,
      value:[]
    },
    inText:{
      type:String,
      value:'入住'
    },
    outText:{
      type: String,
      value: '离店'
    },
    dayUnit:{
      type:String,
      value:'晚'
    }
  },

  attached: function () {
    this.createDateListData();
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({ systemInfo: res });
      }
    })
  },
  ready(){
    this.selectDataMarkLine()
  },
  /**
   * 组件的初始数据
   */
  data: {
    maxMonth: 5, //最多渲染月数
    dateList: [],
    systemInfo: {},
    weekStr: ['日', '一', '二', '三', '四', '五', '六'],
    markcheckInDate: false, //标记开始时间是否已经选择
    markcheckOutDate: false,   //标记结束时间是否已经选择
    totalNight:1,//共几晚

    sFtv: [
      {
        month: 1,
        day: 1,
        name: "元旦"
      },
      {
        month: 2,
        day: 14,
        name: "情人节"
      },
      {
        month: 3,
        day: 8,
        name: "妇女节"
      },
      {
        month: 5,
        day: 1,
        name: "劳动节"
      },
      {
        month: 6,
        day: 1,
        name: "儿童节"
      },
      {
        month: 10,
        day: 1,
        name: "国庆节"
      },
      {
        month: 12,
        day: 24,
        name: "平安夜"
      },
      {
        month: 12,
        day: 25,
        name: "圣诞节"
      }
    ]
  },
  options: {
    multipleSlots: true
  },
  /**
   * 组件的方法列表
   */

  methods: {
    //选择的入住与离店时间段
    selectDataMarkLine: function () {
      let dateList = this.data.dateList;
      let checkInDate = this.data.checkInDate;
      let checkOutDate = this.data.checkOutDate;
    
      let curreInid = checkInDate.substr(0, 4) + "-" + (checkInDate.substr(5, 2) < 10 ? checkInDate.substr(6, 1) : checkInDate.substr(5, 2));//选择入住的id
      let curreOutid = checkOutDate.substr(0, 4) + "-" + (checkOutDate.substr(5, 2) < 10 ? checkOutDate.substr(6, 1) : checkOutDate.substr(5, 2));//选择离店的id
      let dayIn = checkInDate.substr(8, 2) >= 10 ? checkInDate.substr(8, 2) : checkInDate.substr(9, 1);//选择入住的天id
      let dayOut = checkOutDate.substr(8, 2) >= 10 ? checkOutDate.substr(8, 2) : checkOutDate.substr(9, 1);//选择离店的天id
      let monthIn = checkInDate.substr(5, 2) >= 10 ? checkInDate.substr(5, 2) : checkInDate.substr(6, 1);//选择入店的月id
      let monthOut = checkOutDate.substr(5, 2) >= 10 ? checkOutDate.substr(5, 2) : checkOutDate.substr(6, 1);//选择离店的月id
      if (curreInid == curreOutid) {//入住与离店是当月的情况
        for (let i = 0; i < dateList.length; i++) {
          if (dateList[i].id == curreInid) {
            let days = dateList[i].days;
            for (let k = 0; k < days.length; k++) {
              if (days[k].day >= dayIn && days[k].day <= dayOut) {
                days[k].class = days[k].class + ' bgitem';
              }
              if (days[k].day == dayIn) {
                days[k].class = days[k].class + ' active';
                days[k].inday = true;
              }
              if (days[k].day == dayOut) {
                days[k].class = days[k].class + ' active';
                days[k].outday = true;
              }
            }
          }
        }
      } else {//跨月
        for (let j = 0; j < dateList.length; j++) {
          if (dateList[j].month == monthIn) {//入住的开始月份
            let days = dateList[j].days;
            for (let k = 0; k < days.length; k++) {
              if (days[k].day >= dayIn) {
                days[k].class = days[k].class + ' bgitem';
              }
              if (days[k].day == dayIn) {
                days[k].class = days[k].class + ' active';
                days[k].inday = true;
              }
            }
          } else {//入住跨月月份
            if (dateList[j].month < monthOut && dateList[j].month > monthIn) {//离店中间的月份
              let days = dateList[j].days;
              for (let k = 0; k < days.length; k++) {
                days[k].class = days[k].class + ' bgitem';
              }
            } else if (dateList[j].month == monthOut) {//离店最后的月份
              let days = dateList[j].days;
              for (let k = 0; k < days.length; k++) {
                if (days[k].day <= dayOut) {
                  days[k].class = days[k].class + ' bgitem';
                }
                if (days[k].day == dayOut) {
                  days[k].class = days[k].class + ' active';
                  days[k].outday = true;
                }
              }
            }
          }
        }
      }
      this.setData({
        dateList: dateList
      })
    },

    createDateListData: function () {
      var dateList = [];
      var now = new Date();
      /*
        设置日期为 年-月-01,否则可能会出现跨月的问题
        比如：2017-01-31为now ,月份直接+1（now.setMonth(now.getMonth()+1)），则会直接跳到跳到2017-03-03月份.
          原因是由于2月份没有31号，顺推下去变成了了03-03
      */

      //获取当月的第一天
      now = new Date(now.getFullYear(), now.getMonth(), 1);
      for (var i = 0; i < this.data.maxMonth; i++) {
        //获取每个月的第一天
        var momentDate = Moment(now).add(this.data.maxMonth - (this.data.maxMonth - i), 'month').date;
        var year = momentDate.getFullYear();
        var month = momentDate.getMonth() + 1;

        var days = [];
        var totalDay = this.getTotalDayByMonth(year, month);
        //获取每月的第一天是星期几
        var week = this.getWeek(year, month, 1);

        //-week是为了使当月第一天的日期可以正确的显示到对应的周几位置上，比如星期三(week = 3)，
        //则当月的1号是从列的第三个位置开始渲染的，前面会占用-2，-1，0的位置,从1开正常渲染
        for (var j = -week + 1; j <= totalDay; j++) {
          var tempWeek = -1;
          if (j > 0)
            tempWeek = this.getWeek(year, month, j);
          var clazz = '';
          if (tempWeek == 0 || tempWeek == 6)
            clazz = 'week'
          if (j < DATE_DAY && year == DATE_YEAR && month == DATE_MONTH)
            //当天之前的日期不可用
            clazz = 'unavailable ' + clazz;
          else
            clazz = '' + clazz
          days.push({ day: j, class: clazz })
        }
        var dateItem = {
          id: year + '-' + month,
          year: year,
          month: month,
          days: days
        }

        dateList.push(dateItem);
      }
      var sFtv = this.data.sFtv;
      for (let i = 0; i < dateList.length; i++) {//加入公历节日
        for (let k = 0; k < sFtv.length; k++) {
          if (dateList[i].month == sFtv[k].month) {
            let days = dateList[i].days;
            for (let j = 0; j < days.length; j++) {
              if (days[j].day == sFtv[k].day) {
                days[j].daytext = sFtv[k].name
              }
            }
          }
        }
      }
      this.setData({
        dateList: dateList
      });
      DATE_LIST = JSON.parse(JSON.stringify(dateList));
 
      //找到日历中的最后一天
      const dateLen = DATE_LIST.length;
      const year_last = DATE_LIST[dateLen-1].year;
      const month_last = DATE_LIST[dateLen - 1].month < 10 ? '0' + DATE_LIST[dateLen - 1].month : DATE_LIST[dateLen - 1].month;
      let day_last = DATE_LIST[dateLen - 1].days[DATE_LIST[dateLen - 1].days.length-1].day;
      day_last = day_last < 10 ? '0'+day_last : day_last;
      const lastDate = year_last + '-' + month_last + '-' + day_last;
      const params = {
        beginDate: Moment(new Date()).format('YYYY-MM-DD'),
        days: Moment(new Date()).differ(Moment(new Date()).format('YYYY-MM-DD'), lastDate)
      }
      this.triggerEvent('getRoomState', params)
    },

    /*
     * 获取月的总天数
     */
    getTotalDayByMonth: function (year, month) {
      month = parseInt(month, 10);
      var d = new Date(year, month, 0);
      //该月最后一天d
      return d.getDate();
    },
    /*
     * 获取月的第一天是星期几
     */
    getWeek: function (year, month, day) {
      var d = new Date(year, month - 1, day);
      return d.getDay();
    },
    /**
     * 点击日期事件
     */
    onPressDate: function (e) {
      //存储原始入住离开时间最终渲染做判断，是否跨无房
      const originCheckInDate = this.data.checkInDate;
      const originCheckOutDate = this.data.checkOutDate;

      var { year, month, day, state } = e.currentTarget.dataset;
      //当前选择的日期为同一个月并小于今天，或者点击了空白处（即day<0），不执行
      if ((day < DATE_DAY && month == DATE_MONTH) || day <= 0) return;
      var tempMonth = month;
      var tempDay = day;

      if (month < 10) tempMonth = '0' + month
      if (day < 10) tempDay = '0' + day

      var date = year + '-' + tempMonth + '-' + tempDay;

      //如果点击选择的日期A小于等于入住时间，则重新渲染入住时间为A
      if ((this.data.markcheckInDate && Moment(date).before(this.data.checkInDate) || this.data.checkInDate === date)) {
        //入住当天不能为售罄状态
        if (state === 'CLOSE'){
          wx.showToast({
            title: '选择的日期部分订满，请重新选择',
            icon: "none",
            duration: app.globalData.duration
          })
          return
        }
        this.setData({
          markcheckInDate: false,
          markcheckOutDate: false,
          dateList: JSON.parse(JSON.stringify(DATE_LIST)),
          totalNight:0,
          checkOutDate:'',
          checkOutWeek:''
        });
      };

      if (!this.data.markcheckInDate) {
        //入住当天不能为售罄状态
        if (state === 'CLOSE') {
          wx.showToast({
            title: '选择的日期部分订满，请重新选择',
            icon: "none",
            duration: app.globalData.duration
          })
          return
        }
        this.setData({
          checkInDate: date,
          checkInWeek: Moment(new Date()).getWeek(date),
          markcheckInDate: true,
          dateList: JSON.parse(JSON.stringify(DATE_LIST)),
          totalNight: 0,
          checkOutDate: '',
          checkOutWeek: ''
        });
      } else if (!this.data.markcheckOutDate) {
        //如果跨域无房选择
        if (this.hasSoldoutHouse(this.data.checkInDate, date)){
          wx.showToast({
            title: '选择的日期部分订满，请重新选择',
            icon: "none",
            duration: app.globalData.duration
          })
          return
        }
        this.setData({
          checkOutDate: date,
          checkOutWeek: Moment(new Date()).getWeek(date),
          markcheckOutDate: true
        });
        this.selectDataMarkLine();
        //计算共几晚
        this.setData({
          totalNight: Moment(new Date()).differ(this.data.checkInDate, this.data.checkOutDate)
        })
      return
      } else {
        //入住当天不能为售罄状态
        if (state === 'CLOSE') {
          wx.showToast({
            title: '选择的日期 部分订满，请重新选择',
            icon: "none",
            duration: app.globalData.duration
          })
          return
        }
        this.setData({
          checkInDate: date,
          checkInWeek: Moment(new Date()).getWeek(date),
          totalNight: 0,
          checkOutDate: '',
          checkOutWeek: '',
          markcheckInDate: true,
          markcheckOutDate: false,
          dateList: JSON.parse(JSON.stringify(DATE_LIST))
        });
      }

      this.renderPressStyle(year, month, day);
    },
    //渲染入住样式
    renderPressStyle: function (year, month, day) {
      var dateList = this.data.dateList;
      //渲染点击样式
      for (var i = 0; i < dateList.length; i++) {
        var dateItem = dateList[i];
        var id = dateItem.id;
        if (id === year + '-' + month) {
          var days = dateItem.days;
          for (var j = 0; j < days.length; j++) {
            var tempDay = days[j].day;
            if (tempDay == day) {
              days[j].class = days[j].class + ' active';
              days[j].inday = true;
              break;
            }
          }
          break;
        }
      }

      this.setData({
        dateList: dateList
      });
    },
    //确定
    handleConfirm(){
      if (!this.data.totalNight)return
      const params = {
        totalNight: this.data.totalNight,
        checkInDate: this.data.checkInDate,
        checkOutDate: this.data.checkOutDate,
        checkInWeek: this.data.checkInWeek,
        checkOutWeek: this.data.checkOutWeek,
        isSellOut:false
      };
      this.triggerEvent("handleDateConfirm", params)
    },
    //处理已售罄的数据在日历中设为不可选状态
    setSoldOutData() {
      var source = this.data.soldOutList;
      var source_to = DATE_LIST;
      for (var i = 0; i < source.length; i++) {
        var source_date = source[i].date;
        for (var j = 0; j < source_to.length; j++) {
          var nian_j = source_to[j].year;
          var yue_j = source_to[j].month < 10 ? '0' + source_to[j].month : source_to[j].month;
          var ri_j = source_to[j].days;

          var source_to_date;
          for (var m = 0; m < ri_j.length; m++) {
            var ri_m = ri_j[m].day < 10 ? '0' + ri_j[m].day : ri_j[m].day;
            source_to_date = nian_j + "-" + yue_j + "-" + ri_m;
            if (source_date == source_to_date) {
              ri_j[m].state = 'CLOSE';
              ri_j[m].class += ' soldout';
              
              break;
            }
          }
        }
      }
     this.setData({
       dateList: JSON.parse(JSON.stringify(DATE_LIST))
     })
      this.selectDataMarkLine()
    },
    //判断两个日期中间是否有售罄房屋
    hasSoldoutHouse(stime, etime){
      let soldOutList = this.data.soldOutList;
      let dateList = Moment(new Date()).getDiffDate(stime, etime);
      //离店日期可以是无房状态
      dateList.pop();
      let hasCloseHouse = false;
      for(let i = 0;i<dateList.length;i++){
        if (soldOutList.some(o=>{
          return dateList[i]===o.date
        })){
          hasCloseHouse = true;
          break
        }
      }
      return hasCloseHouse
    }
  }
})
